package cn.hchaojie.boot.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import cn.hchaojie.boot.domain.AjaxResult;
import cn.hchaojie.boot.domain.User;
import cn.hchaojie.boot.service.UserService;

@RestController
public class AuthController {
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UserService userService;

	@RequestMapping("/auth/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public AjaxResult auth() {
		return new AjaxResult("401", "请先登陆！");
	}
	
	@RequestMapping("/auth/currentUser")
	public UserDetails me(@AuthenticationPrincipal UserDetails user) {
		return user;
	}
	
	@RequestMapping("/auth/register")
	public AjaxResult register(User user) {
		String passwordEncoded = passwordEncoder.encode(user.getPassword());
		user.setPassword(passwordEncoded);
		userService.register(user);

		return new AjaxResult("200", "注册成功！");
	}
}
